import * as echarts from "echarts";

function setOption(date, count) {
  // 找到最早和最晚的日期
  const minDate = new Date(Math.min(...date));
  const maxDate = new Date(Math.max(...date));

  // 生成完整的年月序列
  const yearMonthSeries = [];
  let currentDate = new Date(minDate);
  while (currentDate <= maxDate) {
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth() + 1;
    yearMonthSeries.push(`${year}-${month.toString().padStart(2, '0')}`);
    currentDate.setMonth(currentDate.getMonth() + 1);
  }

  // 生成年月对应的数据对象
  const dataMap = {};
  for (let i = 0; i < date.length; i++) {
    const key = date[i];
    const year = key.getFullYear();
    const month = key.getMonth() + 1;
    const formattedKey = `${year}-${month.toString().padStart(2, '0')}`;
    dataMap[formattedKey] = count[i];
  }

  // 补充缺失的月份数据
  yearMonthSeries.forEach(yearMonth => {
    if (!dataMap[yearMonth]) {
      dataMap[yearMonth] = 0;
    }
  });

  // 将数据按照年月排序
  const sortedDataMap = Object.fromEntries(Object.entries(dataMap).sort());

  // 生成最终的 x 轴和数据
  const xAxisData = Object.keys(sortedDataMap);
  const seriesData = xAxisData.map(key => sortedDataMap[key]);

  let option = {
    tooltip: {
      trigger: 'axis'
    },
    title: {
      text: '每月诉求数统计',
      left: '5%',
      top: '5%',
      textStyle: {
        color: '#007AFF',
        fontSize: 16
      }
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      axisLabel: {
        formatter: function (value, index) {
          const parts = value.split('-');
          if (parts[1] === '01') {
            return parts[0] + '年';
          } else {
            return parts[1] + '月';
          }
        }
      }
    },
    yAxis: {
      type: 'value'
    },
    grid: {
      left: '3%',
      right: '8%',
      bottom: '10%',
      containLabel: true
    },
    series: [
      {
        name: '诉求数',
        data: seriesData,
        type: 'line',
        showBackground: true,
        itemStyle: {
          color: '#0262F7'
        },
        label: {
          show: true,
          position: 'top',
          color: '#000'
        },
        backgroundStyle: {
          color: 'rgba(180, 180, 180, 0.2)'
        }
      }
    ],
    

  };
  return option;
}

export default {
  setOption
};